let utils = {};

utils.getRouterObjByName = function(routers, name) {
	if(!name || !routers || !routers.length) {
		return null;
	}
	// debugger;
	let routerObj = null;
	for(let item of routers) {
		if(item.name === name) {
			return item;
		}
		routerObj = utils.getRouterObjByName(item.children, name);
		if(routerObj) {
			return routerObj;
		}
	}
	return null;
};

utils.unique = function (arr, key) {
  let map = new Map();
  let array = new Array();  // 数组用于返回结果
  arr.forEach(e=>{
    let id = e[key];
    if(!map[id]){
      array.push(e);
      map[id] = true;
    }
  })
  return array ;
}

utils.formatDate = function(date, fmt) {
	if(date == null || date == "") return "";
  fmt = fmt||"yyyy-MM-dd hh:mm";
	if(/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
	}
	let o = {
		'M+': date.getMonth() + 1,
		'd+': date.getDate(),
		'h+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds()
	};
	for(let k in o) {
		if(new RegExp(`(${k})`).test(fmt)) {
			let str = o[k] + '';
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : utils.padLeftZero(str));
		}
	}
	return fmt;
}
utils.padLeftZero = function(str) {
	return('00' + str).substr(str.length);
}

utils.getNearDay = (type) => {
	var result = "";
	if(type == "today") {
		//获取系统当前时间
		var nowdate = new Date();
		var Ty = nowdate.getFullYear();
		var Tm = nowdate.getMonth() + 1;
		var Td = nowdate.getDate();
		if(Tm <= 9) {
			Tm = "0" + Tm;
		}
		if(Td <= 9) {
			Td = "0" + Td;
		}
		result = Ty + "-" + Tm + "-" + Td;
	} else if(type == "yesterday") {
		var timenow = new Date();
		timenow.setDate(timenow.getDate() - 1); //设置天数 -1 天，昨天的日期
		var y = timenow.getFullYear(); //年
		var m = timenow.getMonth() + 1; //月
		m = m < 10 ? "0" + m : m;
		var d = timenow.getDate(); //日
		d = d < 10 ? "0" + d : d;
		result = y + "-" + m + "-" + d; //字符串拼接成自己想要的时间格式，现在是yyyy/mm/dd格式
	} else if(type == "nearWeek") {
		var nowdate = new Date();
		var nearweekdate = new Date(nowdate - 7 * 24 * 3600 * 1000);
		var nearw_y = nearweekdate.getFullYear();
		var nearw_m = nearweekdate.getMonth() + 1;
		var nearw_d = nearweekdate.getDate();
		if(nearw_m <= 9) {
			nearw_m = "0" + nearw_m;
		}
		if(nearw_d <= 9) {
			nearw_d = "0" + nearw_d;
		}
		result = nearw_y + "-" + nearw_m + "-" + nearw_d;
	} else if(type == "nearMouth") {
		var nowdate = new Date();
		//获取近一月时间
		nowdate.setMonth(nowdate.getMonth() - 1);
		var nearm_y = nowdate.getFullYear();
		var nearm_m = nowdate.getMonth() + 1;
		var nearm_d = nowdate.getDate();
		if(nearm_m <= 9) {
			nearm_m = "0" + nearm_m;
		}
		if(nearm_d <= 9) {
			nearm_d = "0" + nearm_d;
		}
		result = nearm_y + "-" + nearm_m + "-" + nearm_d;
	} else if(type == "nearYear") {
		var localdate = new Date(); //Sat Jul 20 2013 10:43:36 GMT+0800 (中国标准时间)
		var lastyear = new Date(localdate - 365 * 24 * 60 * 60 * 1000); //Fri Jul 20 2012 10:43:36 GMT+0800 (中国标准时间) 减一个月只需要把365改为30即可
		var year = lastyear.getFullYear(); //2012
		var month = lastyear.getMonth() + 1; //7
		var month = month < 10 ? "0" + month : month; //"07"
		var day = lastyear.getDate(); //20
		var day = day < 10 ? "0" + day : day; //"20"
		result = year + "-" + month + "-" + day; //"2012-07-20"
	}
	return result;
}

utils.sortFun = function(key, orderBy) {
	return function(a, b) {
		var val1 = a;
		var val2 = b;
		if(key != null && key != "") {
			val1 = a[key];
			val2 = b[key];
		}
		if(orderBy == "desc") {
			if(val1 < val2) { //降序
				return 1;
			} else if(val1 > val2) {
				return -1;
			} else {
				return 0;
			}
		} else if(orderBy == "asc") {
			if(val1 > val2) { //升序
				return 1;
			} else if(val1 < val2) {
				return -1;
			} else {
				return 0;
			}
		}
	}
}

utils.sortDescByKey = function(key) {
	return function(a, b) {
		var val1 = a[key];
		var val2 = b[key];
		if(val1 < val2) { //降序
			return 1;
		} else if(val1 > val2) {
			return -1;
		} else {
			return 0;
		}
	}
}

utils.sortDesc = function() {
	return function(a, b) {
		var val1 = a;
		var val2 = b;
		if(val1 < val2) { //降序
			return 1;
		} else if(val1 > val2) {
			return -1;
		} else {
			return 0;
		}
	}
}

utils.sortAscByKey = function(key) {
	return function(a, b) {
		var val1 = a[key];
		var val2 = b[key];
		if(val1 > val2) { //升序
			return 1;
		} else if(val1 < val2) {
			return -1;
		} else {
			return 0;
		}
	}
}

utils.sortAsc = function() {
	return function(a, b) {
		var val1 = a;
		var val2 = b;
		if(val1 > val2) { //升序
			return 1;
		} else if(val1 < val2) {
			return -1;
		} else {
			return 0;
		}
	}
}

utils.sort = function(data, key, order) {
	if(order == "desc") {
		if(key == "") return data.sort(utils.sortDesc());
		else return data.sort(utils.sortDescByKey(key));
	} else if(order == "asc") {
		if(key == "") return data.sort(utils.sortAsc());
		else return data.sort(utils.sortAscByKey(key));
	} else return data;
}

utils.isDeviceMobile = function() {
	let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
	return flag;
}
utils.isMobile = function(val) {
    return val && (/^1[34578]\d{9}$/i.test(val));
}
utils.sensorsTypeKeyName = {};

utils.sensorsKeyName = {};

utils.initAllSensorType = (vm) => {
	vm.$http.send({
		url: "/api/showAllSensorTableEntity",
		params: {
			pageNum: 0,
			pageSize: 5
		}
	}, vm, res => {
		var data = res.data;
		var units = utils.sensorsUnitName;
		var unitsKeyName = {};
		units.forEach(e => {
			unitsKeyName[e.sensorsValue] = e.unit;
		});
		data.forEach(e => {
			var types = e.moniterType.split(',');
			var names = e.name.split('/');
			utils.sensorsTypeKeyName[e.id] = [];
			var i = 0;
			types.forEach(t => {
				utils.sensorsTypeKeyName[e.id].push({
					name: names[i],
					key: t,
					unit: unitsKeyName[t]
				});
				utils.sensorsKeyName[t] = names[i];
				i++;
			})
		});
		// console.log(utils.sensorsTypeKeyName);
	});
}

utils.render_zrdw = function(e, h) {
	var nbm = (e.pqs && e.pqs.length);
	if(nbm) {
		var bm = e.pqs[0];
		if(nbm == 1) {
			return h('div', [
				h('p', {
					style: {
						fontWeight: 700,
						color: 'darkgreen'
					}
				}, bm.bm_title),
				h('p', {
					style: {}
				}, bm.pqsj),
				h('p', {
					style: {}
				}, bm.czqk),
			]);
		} else {
			return h('div', [
				h('p', {
					style: {
						fontWeight: 700,
						color: 'darkgreen'
					}
				}, bm.bm_title),
				h('p', {
					style: {}
				}, bm.pqsj),
				h('p', {
					style: {}
				}, bm.czqk),
				h('p', {
					style: {
						fontWeight: 700
					}
				}, "..."),
			]);
		}
	} else {
		return h('div', [
			h('p', {
				style: {
					fontWeight: 800,
					color: 'darkgreen'
				}
			}, "未派遣"),
		]);
	}
}

/*对Date的扩展，将 Date 转化为指定格式的String
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
//年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
//例子：
//(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
//(new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18*/
// if(!Date.prototype.Format)
Date.prototype.Format = function(fmt) { //author: meizz
  fmt = fmt || "yyyy-MM-dd hh:mm:ss";
	var o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours(), //小时
		"H+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};
	if(/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for(var k in o)
		if(new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}
// utils.formatDate = function(date, fmt) {
// 	if(fmt) {
// 		return date.Format(fmt);
// 	}
// 	return date.Format("yyyy-MM-dd");
// }
// utils.formatDate = function(date, fmt) {
// 	if(date == null || date == "") return "";
//   fmt = fmt||"yyyy-MM-dd hh:mm";
// 	if(/(y+)/.test(fmt)) {
// 		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
// 	}
// 	let o = {
// 		'M+': date.getMonth() + 1,
// 		'd+': date.getDate(),
// 		'h+': date.getHours(),
// 		'm+': date.getMinutes(),
// 		's+': date.getSeconds()
// 	};
// 	for(let k in o) {
// 		if(new RegExp(`(${k})`).test(fmt)) {
// 			let str = o[k] + '';
// 			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : utils.padLeftZero(str));
// 		}
// 	}
// 	return fmt;
// }
utils.formatDatetime = function(date, fmt) {
	if(fmt) {
		return date.Format(fmt);
	}
	return date.Format("yyyy-MM-dd hh:mm:ss");
}
utils.formatTimestamp = function(date, fmt) {
	if(fmt) {
		return date.Format(fmt);
	}
	return date.Format("yyyy-MM-dd hh:mm:ss.S");
}

utils.date = function() {

	/**
	 * 获取本周、本季度、本月、上月的开端日期、停止日期
	 */
	var now = new Date(); //当前日期
	var nowDayOfWeek = now.getDay(); //今天本周的第几天
	var nowDay = now.getDate(); //当前日
	var nowMonth = now.getMonth(); //当前月
	var nowYear = now.getYear(); //当前年
	nowYear += (nowYear < 2000) ? 1900 : 0; //

	var lastMonthDate = new Date(); //上月日期
	lastMonthDate.setDate(1);
	lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
	var lastYear = lastMonthDate.getYear();
	var lastMonth = lastMonthDate.getMonth();

	//格局化日期：yyyy-MM-dd
	function formatDate(date) {
		date = (date || now);
		var myyear = date.getFullYear();
		var mymonth = date.getMonth() + 1;
		var myweekday = date.getDate();

		if(mymonth < 10) {
			mymonth = "0" + mymonth;
		}
		if(myweekday < 10) {
			myweekday = "0" + myweekday;
		}
		return(myyear + "-" + mymonth + "-" + myweekday);
	}

	//获得某月的天数
	function getMonthDays(myMonth) {
		var monthStartDate = new Date(nowYear, myMonth, 1);
		var monthEndDate = new Date(nowYear, myMonth + 1, 1);
		var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
		return days;
	}
	this.getMonthDays = getMonthDays;

	this.getToday = function() {
		return formatDate(now);
	}
	this.getLastday = function() {
		var lastDate = new Date(nowYear, nowMonth, nowDay - 1);
		return formatDate(lastDate);
	}
	this.getLastnday = function(n) {
		var lastDate = new Date(nowYear, nowMonth, nowDay - n);
		return formatDate(lastDate);
	}

	this.getThisYearStartDate = function() {
		var lastDate = new Date(nowYear, 0, 1);
		return formatDate(lastDate);
	}
	this.getThisYearEndDate = function() {
		var lastDate = new Date(nowYear, 11, 31);
		return formatDate(lastDate);
	}
	this.getLastYearStartDate = function() {
		var lastDate = new Date(nowYear - 1, 0, 1);
		return formatDate(lastDate);
	}
	this.getLastYearEndDate = function() {
		var lastDate = new Date(nowYear - 1, 11, 31);
		return formatDate(lastDate);
	}

	//获得本季度的开端月份
	function getQuarterStartMonth() {
		var quarterStartMonth = 0;
		if(nowMonth < 3) {
			quarterStartMonth = 0;
		}
		if(2 < nowMonth && nowMonth < 6) {
			quarterStartMonth = 3;
		}
		if(5 < nowMonth && nowMonth < 9) {
			quarterStartMonth = 6;
		}
		if(nowMonth > 8) {
			quarterStartMonth = 9;
		}
		return quarterStartMonth;
	}
	this.getQuarterStartMonth = getQuarterStartMonth;

	//获得本周的开端日期
	function getWeekStartDate() {
		var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
		return formatDate(weekStartDate);
	}

	//获得本周的停止日期
	function getWeekEndDate() {
		var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
		return formatDate(weekEndDate);
	}
	this.getWeekStartDate = getWeekStartDate;
	this.getWeekEndDate = getWeekEndDate;

	//获得上周的开始日期
	function getLastWeekStartDate() {
		var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7);
		return formatDate(weekStartDate);
	}
	//获得上周的结束日期
	function getLastWeekEndDate() {
		var weekEndDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 1);
		return formatDate(weekEndDate);
	}
	this.getLastWeekStartDate = getLastWeekStartDate;
	this.getLastWeekEndDate = getLastWeekEndDate;

	//获得本月的开端日期
	function getMonthStartDate() {
		var monthStartDate = new Date(nowYear, nowMonth, 1);
		return formatDate(monthStartDate);
	}

	//获得本月的停止日期
	function getMonthEndDate() {
		var monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth));
		return formatDate(monthEndDate);
	}
	this.getMonthStartDate = getMonthStartDate;
	this.getMonthEndDate = getMonthEndDate;

	//获得上月开端时候
	function getLastMonthStartDate() {
		var lastMonthStartDate = new Date(nowYear, lastMonth, 1);
		return formatDate(lastMonthStartDate);
	}

	//获得上月停止时候
	function getLastMonthEndDate() {
		var lastMonthEndDate = new Date(nowYear, lastMonth, getMonthDays(lastMonth));
		return formatDate(lastMonthEndDate);
	}
	this.getLastMonthStartDate = getLastMonthStartDate;
	this.getLastMonthEndDate = getLastMonthEndDate;

	//获得本季度的开端日期
	function getQuarterStartDate() {

		var quarterStartDate = new Date(nowYear, getQuarterStartMonth(), 1);
		return formatDate(quarterStartDate);
	}

	//或的本季度的停止日期
	function getQuarterEndDate() {
		var quarterEndMonth = getQuarterStartMonth() + 2;
		var quarterStartDate = new Date(nowYear, quarterEndMonth, getMonthDays(quarterEndMonth));
		return formatDate(quarterStartDate);
	}

	this.getQuarterStartDate = getQuarterStartDate;
	this.getQuarterEndDate = getQuarterEndDate;

	this.getLastQuarterStartDate = function() {
		var quarterStartDate = new Date(nowYear, getQuarterStartMonth() - 3, 1);
		return formatDate(quarterStartDate);
	}

	//或的本季度的停止日期
	this.getLastQuarterEndDate = function() {
		var quarterEndMonth = getQuarterStartMonth() + 2 - 3;
		var quarterStartDate = new Date(nowYear, quarterEndMonth, getMonthDays(quarterEndMonth));
		return formatDate(quarterStartDate);
	}

	this.getDateRange = function(tag) {
		var myDate = this;
		var s = '2000-01-01';
		var e = '2050-01-01';
		switch(tag) {
			case "today":
				{
					s = e = myDate.getToday();
					break;
				}
			case "yesterday":
				{
					s = e = myDate.getLastday();
					break;
				}
			case "last3day":
				{
					s = myDate.getLastnday(2);
					e = myDate.getToday();
					break;
				}
			case "this-week":
				{
					s = myDate.getWeekStartDate();
					e = myDate.getWeekEndDate();
					break;
				}
			case "last-week":
				{
					s = myDate.getLastWeekStartDate();
					e = myDate.getLastWeekEndDate();
					break;
				}
			case "this-month":
				{
					s = myDate.getMonthStartDate();
					e = myDate.getMonthEndDate();
					break;
				}
			case "last-month":
				{
					s = myDate.getLastMonthStartDate();
					e = myDate.getLastMonthEndDate();
					break;
				}
			case "this-quater":
				{
					s = myDate.getQuarterStartDate();
					e = myDate.getQuarterEndDate();
					break;
				}
			case "last-quater":
				{
					s = myDate.getLastQuarterStartDate();
					e = myDate.getLastQuarterEndDate();
					break;
				}
			case "this-year":
				{
					s = myDate.getThisYearStartDate();
					e = myDate.getThisYearEndDate();
					break;
				}
			case "last-year":
				{
					s = myDate.getLastYearStartDate();
					e = myDate.getLastYearEndDate();
					break;
				}
			default:
				break;
		}
		return {s:s, e:e, tag:tag};
	}

};

utils.isMobile = function(val) {
    return val && (/^1[345789]\d{9}$/i.test(val));
}
utils.isEmail = function(val) {
    return val && (/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i.test(val));
}
utils.isIdCard = function(val) {
    return val && (/^[1-9]\d{5}(19\d{2}|[2-9]\d{3})((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])(\d{4}|\d{3}X)$/i.test(val));
}

import dateUtils from "./dateUtils.js"

utils.dateUtils = dateUtils

export default utils;

export function isDirty(val, raw) {
  val = val || {}
  let keys = Object.keys(val)
  for (let i = 0; i < keys.length; ++i) {
    let k = keys[i]
    if (val[k] != raw[k]) {
      return true;
    }
  }
  return false
}
